<template>
    <el-dialog class="create_template_dialog" :title="title" v-model="visible" width="80%" @close="handleVisible()">
        <template v-if="!selected">
            <div class="create_template_dialog_header">
                <el-form ref="formRef" :model="form" label-width="auto" @submit.prevent>
                    <el-row justify="space-between">
                        <el-col>
                            <el-form-item label="模板标题：" prop="title">
                                <el-input v-model="form.keyword" clearable placeholder="请输入模板标题"></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col style="margin-left: 24px">
                            <el-button type="primary" @click="searchHandler">查询</el-button>
                        </el-col>
                    </el-row>
                </el-form>
                <div>
                    <span v-if="!!syncDate" style="margin-right: 10px; color: #aaa"
                        >最近一次同步时间：{{ syncDate }}</span
                    >
                    <el-tooltip
                        v-model:visible="tooltipVisible"
                        effect="dark"
                        :virtual-ref="buttonRef"
                        placement="top"
                        trigger="click"
                        virtual-triggering
                        :content="syncContext">
                    </el-tooltip>
                    <el-button ref="buttonRef" @click="handleSync">同步公共模版</el-button>
                </div>
            </div>
            <el-table :data="tableList">
                <el-table-column v-for="{ prop, ...rest } in tableColumns" :key="prop" :prop="prop" v-bind="rest">
                    <template v-if="prop === 'operations'" #default="{ row }">
                        <el-button size="small" @click="handleSelect(row)">选择</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <!-- 分页 -->
            <div style="margin-top: 15px">
                <Pagination
                    :total="totalCount"
                    :page-size="form.perPage"
                    :current-page="form.page"
                    @sizeChange="changeSizeHandler"
                    @pageChange="changePageHandler" />
            </div>
        </template>
        <template v-else>
            <div class="select-keyword">
                <div class="select-keyword-left">
                    <div class="select-keyword-left-top">
                        <div>关键词</div>
                        <div>
                            <div class="select-keyword-search">
                                <el-input v-model="word" placeholder="输入关键词查询"></el-input>
                                <el-button type="primary" @click="handleSearch">查询</el-button>
                            </div>
                            <div>
                                <el-checkbox
                                    v-for="{ kid, name, rule } in keywordsFilter"
                                    :key="kid"
                                    :disabled="isDisabled(kid)"
                                    @change="handleCheck($event, { kid, name, rule })">
                                    {{ name }}
                                </el-checkbox>
                            </div>
                        </div>
                    </div>
                    <div class="select-keyword-left-bottom">
                        <div>已选择（{{ selectedLength }}/5）</div>
                        <div>
                            <template v-if="selectedLength <= 0"> 请选择上方关键词 </template>
                        </div>
                        <draggable :list="selectedKeywords" :options="sortOptions" item-key="kid" style="width: 100%">
                            <template #item="{ element }">
                                <div class="drag-item">
                                    {{ element.name }}
                                    <img src="@/assets/imgs/sys/drag-icon.png" style="width: 16px" alt="" />
                                </div>
                            </template>
                        </draggable>
                    </div>
                </div>
                <div class="select-keyword-right">
                    <div class="select-keyword-right-title">
                        <img
                            src="@/assets/imgs/sys/wechat-dark-icon.png"
                            style="width: 16px; margin-right: 6px"
                            alt="" />
                        小程序名称
                    </div>
                    <div class="select-keyword-right-scroll">
                        <h5>{{ selectRow.title }}</h5>
                        <div v-for="{ kid, name } in selectedKeywords" :key="kid">
                            <span>{{ name }}</span
                            ><span>{{ '{' + name + '}' }}</span>
                        </div>
                    </div>
                    <div class="select-keyword-right-view">
                        查看详情
                        <el-icon><ArrowRight /></el-icon>
                    </div>
                </div>
            </div>
        </template>
        <template #footer v-if="selected">
            <span class="dialog-footer">
                <el-button @click="handleVisible()">取消</el-button>
                <!-- todo:弹窗 -->
                <el-button
                    v-if="!selectedKeywords || !selectedKeywords.length || selectedKeywords.length < 2"
                    type="primary"
                    @click="handleConfirm"
                    >确认</el-button
                >
                <el-popconfirm
                    icon="WarningFilled"
                    placement="top"
                    width="250px"
                    title="保存后，关键词和顺序将无法修改。确定要保存吗？"
                    @confirm="handleConfirm"
                    confirm-button-text="确定"
                    cancel-button-text="取消"
                    v-if="selectedKeywords && selectedKeywords.length && selectedKeywords.length > 1">
                    <template #reference>
                        <el-button
                            type="primary"
                            v-if="selectedKeywords && selectedKeywords.length && selectedKeywords.length > 1"
                            >确认</el-button
                        >
                    </template>
                </el-popconfirm>
            </span>
        </template>
    </el-dialog>
</template>
<script setup>
import { reactive, ref, unref, computed, watch } from 'vue';
import draggable from 'vuedraggable';
import request from '@/request/index';
import { ElMessage } from 'element-plus';
import Pagination from '@/components/Pagination.vue';

const props = defineProps({
    modelValue: Boolean
});

const emit = defineEmits(['update:modelValue']);

let visible = ref(false);
let tooltipVisible = ref(false);
const formRef = ref();
const form = reactive({
    keyword: '',
    page: 1,
    perPage: 10
});
let syncContext = ref('');
const buttonRef = ref();
const totalCount = ref(0);
let tableList = reactive([]);
const tableColumns = reactive([
    { label: '标题', prop: 'title', showOverflowTooltip: true, width: '250' },
    { label: '服务类目', prop: 'categoryName', showOverflowTooltip: true },
    { label: '操作', prop: 'operations', width: '100' }
]);
let selected = ref(false);
let selectRow = reactive({});
let syncDate = ref('');
let keywords = reactive([]);
let selectedKeywords = reactive([]);
const sortOptions = reactive({
    animation: 150,
    ghostClass: 'sortable-ghost',
    chosenClass: 'sortable-chosen',
    dragClass: 'sortable-drag'
});
let word = ref(null);
let params = reactive({});

const title = computed(() => {
    return `选择模板${selected.value ? '关键词' : ''}`;
});
const selectedLength = computed(() => {
    return selectedKeywords.length;
});
const keywordsFilter = computed(() => {
    return keywords.filter(item => item.name.includes(unref(word) || ''));
});

watch(
    () => props.modelValue,
    val => {
        if (val) {
            getTemplateData();
        } else {
            selected.value = false;
            word.value = null;
            keywords.length = 0;
            selectedKeywords.length = 0;
            form.page = 1;
            form.keyword = '';
            visible.value = false;
            Object.assign(selectRow, {});
        }
    }
);

const searchHandler = () => {
    // 查询
    form.page = 1;
    getTemplateData();
};
const handleSync = async () => {
    // 立即同步
    const { data } = await request('miniappMsgTplSync');
    syncContext.value = data.statusName;
    tooltipVisible.value = !!data.statusName;
    // 同步时间处理，tooltip窗口处理
    if (data.status == 3) {
        syncDate.value = data.syncDate;
        getTemplateData();
    }
};
const openGetTemplate = async () => {
    getTemplateData();
};
const getTemplateData = async () => {
    // 获取模板
    try {
        const { data } = await request('miniappMsgTpl', form);
        tableList.length = 0;
        Object.assign(tableList, data.list);
        totalCount.value = data.totalCount;
        visible.value = true;
        // 同步时间处理
        syncDate.value = data.syncDate || '';
    } catch {
        handleVisible(false);
    }
};
/**
 * 分页
 * @param {*} page
 */
const changePageHandler = page => {
    form.page = page;
    getTemplateData();
};

/**
 * 每页记录数修改
 * @param {*} perPage
 */
const changeSizeHandler = perPage => {
    form.page = 1;
    form.perPage = perPage;
    getTemplateData();
};
const handleSearch = async () => {};
const handleSelect = async ({ tid, categoryId, title }) => {
    Object.assign(selectRow, { tid, title });
    const { data } = await request('miniappMsgTplKeywords', { tid, categoryId });
    Object.assign(keywords, data.list);
    selected.value = true;
};
const isDisabled = kid => {
    return unref(selectedLength) === 5 && !selectedKeywords.map(item => item.kid).includes(kid);
};
const handleCheck = (val, row) => {
    if (val) {
        selectedKeywords.push(row);
        return;
    }
    selectedKeywords.splice(
        selectedKeywords.findIndex(item => item.kid == row.kid),
        1
    );
};
const handleVisible = (visible = false) => {
    emit('update:modelValue', visible);
};
const handleConfirm = async () => {
    if (!selectedKeywords || !selectedKeywords.length || selectedKeywords.length < 2) {
        ElMessage({
            type: 'error',
            message: '请至少选择两个关键词'
        });
        return;
    }
    let reqQuery = {
        ...selectRow,
        sceneDesc: '小程序商城',
        keywordList: selectedKeywords
    };
    await request('miniappMsgTplAdd', reqQuery);
    handleVisible(false);
    emit('handle-refresh');
};
</script>
<style lang="scss">
.create_template_dialog {
    max-width: 1000px;
    min-width: 900px;
}
</style>
<style lang="scss" scoped>
%scroll {
    &::-webkit-scrollbar {
        width: 5px;
        height: 40px;
    }
    &::-webkit-scrollbar-track {
        background: #fff;
        border-radius: 3px;
    }
    &::-webkit-scrollbar-thumb {
        background: #d8d8d8;
        border-radius: 3px;
    }
    &::-webkit-scrollbar-thumb:hover {
        background: #333;
    }
    &::-webkit-scrollbar-corner {
        background: #179a16;
    }
}
.create_template_dialog {
    &_header {
        display: flex;
        justify-content: space-between;
        .el-form > div {
            flex-wrap: nowrap;
        }
    }
    .select-keyword {
        display: flex;
        justify-content: space-between;
        &-left {
            flex: 1;
            margin-right: 64px;
            &-top,
            &-bottom {
                display: flex;
                & > div {
                    &:first-of-type {
                        width: 100px;
                        font-size: 14px;
                        font-family: PingFangSC-Regular, PingFang SC;
                        font-weight: 400;
                        color: #33302d;
                    }
                    &:last-of-type {
                        flex: 1;
                        border-radius: 4px;
                    }
                }
            }
            &-top {
                margin-bottom: 24px;
            }
            &-top > div:last-of-type {
                padding: 20px;
                max-height: 246px;
                min-height: 100px;
                border: 1px solid #eaeaea;
                .select-keyword-search {
                    display: flex;
                    margin-bottom: 16px;
                    .el-button {
                        margin-left: 24px;
                    }
                }
                .select-keyword-search + div {
                    display: flex;
                    flex-direction: column;
                    max-height: 190px;
                    overflow-y: auto;
                    @extend %scroll;
                    .el-checkbox {
                        height: auto;
                        margin-bottom: 16px;
                    }
                }
            }
            &-bottom > div:last-of-type {
                .drag-item {
                    margin-top: -1px;
                    height: 54px;
                    display: flex;
                    justify-content: space-between;
                    align-items: center;
                    padding: 0 24px;
                    border: 1px solid #eaeaea;
                    cursor: move;
                }
            }
        }
        &-right {
            flex: 1;
            max-width: 364px;
            min-width: 280px;
            height: 336px;
            background: #ffffff;
            border: 1px solid #eaeaea;
            display: flex;
            flex-direction: column;
            &-title {
                padding-left: 24px;
                display: flex;
                align-items: center;
                height: 56px;
                font-size: 16px;
                font-family: PingFangSC-Regular, PingFang SC;
                font-weight: 400;
                color: #33302d;
            }
            &-scroll {
                flex: 1;
                overflow-y: auto;
                border-top: 1px solid #eaeaea;
                border-bottom: 1px solid #eaeaea;
                padding: 16px 24px;
                @extend %scroll;
                h5 {
                    font-size: 14px;
                    font-family: PingFangSC-Medium, PingFang SC;
                    font-weight: 500;
                    color: #33302d;
                    margin: 0;
                    margin-bottom: 16px;
                }
                & > div {
                    margin-bottom: 16px;
                    display: flex;
                    justify-content: space-between;
                    align-items: flex-start;
                    span {
                        font-size: 14px;
                        font-family: PingFangSC-Regular, PingFang SC;
                        font-weight: 400;
                        color: #969696;
                        &:last-of-type {
                            color: #33302d;
                            margin-left: 8px;
                            word-break: break-all;
                            max-width: 200px;
                        }
                    }
                }
            }
            &-view {
                display: flex;
                justify-content: space-between;
                padding: 0 24px;
                align-items: center;
                height: 48px;
                font-size: 14px;
                font-family: PingFangSC-Regular, PingFang SC;
                font-weight: 400;
                color: #969696;
            }
        }
    }
}
</style>
